package com.juyu.miliao.common.delay;

import lombok.Getter;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟消息体消息体定义
 * @param <T>
 * @author xuanqicheng
 */
@Getter
public class DelayMessage<T> implements Delayed {
    /**
     * 消息编号
     */
    private int id;
    /**
     * 消息内容
     */
    private T body;
    /**
     * 到期日期时间戳
     */
    private long expireTime;


    public DelayMessage(int id, T body, long expireTime) {
        this.id = id;
        this.body = body;
        this.expireTime = expireTime;
    }

    /**
     * 自定义实现比较方法
     *
     * @param delayed
     * @return
     */
    @Override
    public int compareTo(Delayed delayed) {
        DelayMessage other = (DelayMessage) delayed;
        long diff = expireTime - other.expireTime;
        if (diff > 0) {
            return 1;
        } else if (diff < 0) {
            return -1;
        } else {
            return 0;
        }
        //return (int) (this.getDelay(TimeUnit.MILLISECONDS) - delayed.getDelay(TimeUnit.MILLISECONDS));
    }

    /**
     * 延迟任务是否到时就是按照这个方法判断如果返回的是负数则说明到期否则还没到期
     *
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expireTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);

    }
}
